package com.ztz.mynewdemo;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.balysv.materialmenu.MaterialMenuDrawable;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ztz.mynewdemo.activity.AboutMeActivity;
import com.ztz.mynewdemo.activity.BaseActivity;
import com.ztz.mynewdemo.activity.CollectActivity;
import com.ztz.mynewdemo.activity.DynaActivity;
import com.ztz.mynewdemo.activity.LocateActivity;
import com.ztz.mynewdemo.activity.ScanActivity;
import com.ztz.mynewdemo.activity.ShakeActivity;
import com.ztz.mynewdemo.adapter.MyAdapter;
import com.ztz.mynewdemo.bean.MyDatabaseHelper;
import com.ztz.mynewdemo.bean.PersonInfoResponse;
import com.ztz.mynewdemo.fragment.JokeFragment;
import com.ztz.mynewdemo.fragment.NewsFragment;
import com.ztz.mynewdemo.fragment.NullFragment;
import com.ztz.mynewdemo.fragment.RecommendFrag;
import com.ztz.mynewdemo.fragment.ShowCodeFragment;
import com.ztz.mynewdemo.fragment.TodayHistoryFrag;
import com.ztz.mynewdemo.fragment.ZhanKuFragment;
import com.ztz.mynewdemo.utils.AppConfigUtils;
import com.ztz.mynewdemo.utils.DataClearManagerUtils;
import com.ztz.mynewdemo.utils.GlideCircleTransform;
import com.ztz.mynewdemo.utils.NewsApi;
import com.ztz.mynewdemo.utils.OkHttpUtils;
import com.ztz.mynewdemo.utils.RequestUtils;
import com.ztz.mynewdemo.widget.UnScrollViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    public static final String DESIGN = "DESIGN";
    DrawerLayout mDawLayout;
    Toolbar toolbar;
    BottomNavigationBar bl;
    UnScrollViewPager unScroll;
    //    BottomLayout bottomLayout;
    MyAdapter adapter;
    List<Fragment> fragmentList = new ArrayList<>();
    //    List<TabBean> tabBeanLis=new ArrayList<>();
    MyDatabaseHelper dbHelper;
    Calendar calendar;
    TodayHistoryFrag todayFrag;
    private boolean isDrawerOpened;
    int year, month, day;
    private MaterialMenuDrawable materialMenu;
    TextView tv_header;
    ImageView navImage;
    private byte[] mImageBytes = null;
    private Boolean isWifiConn;
    private Boolean isMobileConn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main2);
        todayFrag = new TodayHistoryFrag();
        NavigationView nav = (NavigationView) findViewById(R.id.nav_view);
        //通过此方法获取NavigationView头部的控件id
        View headView = nav.getHeaderView(0);
        tv_header = (TextView) headView.findViewById(R.id.tv_header);
        navImage = (ImageView) headView.findViewById(R.id.nav_image);
        Glide.with(MainActivity.this)
                .load(R.mipmap.bxbxbai)
                .centerCrop()
                .transform(new GlideCircleTransform(MainActivity.this))
                .into(navImage);
        mDawLayout = (DrawerLayout) findViewById(R.id.draw_layout);
        unScroll = (UnScrollViewPager) findViewById(R.id.unSrc);
        bl = (BottomNavigationBar) findViewById(R.id.bottom_Bar);
//        bottomLayout=(BottomLayout)findViewById(R.id.bottom_lay);
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
//        CrashReport.testJavaCrash();
        dbHelper = new MyDatabaseHelper(this, "CollectionStore.db", null, 4);
//        ActionBar actionBar=getSupportActionBar();
//        if(actionBar!=null){
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
        //NetworkInfo对象包含网络连接的所有信息
        //步骤3：根据需要取出网络连接信息
        //获取WIFI连接的信息
        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        isWifiConn = networkInfo.isConnected();

        //获取移动数据连接的信息
        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        isMobileConn = networkInfo.isConnected();
        materialMenu = new MaterialMenuDrawable(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN);
        toolbar.setNavigationIcon(materialMenu);
        mDawLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                materialMenu.setTransformationOffset(MaterialMenuDrawable.AnimationState.BURGER_ARROW,
                        isDrawerOpened ? 2 - slideOffset : slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                isDrawerOpened = true;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawerOpened = false;
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                if (newState == DrawerLayout.STATE_IDLE) {
                    if (isDrawerOpened) {
                        materialMenu.setIconState(MaterialMenuDrawable.IconState.ARROW);
                    } else {
                        materialMenu.setIconState(MaterialMenuDrawable.IconState.BURGER);
                    }
                }
            }
        });
        nav.setNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.menu_collect:
//                       dbHelper.getWritableDatabase();
                    Intent i = new Intent(MainActivity.this, CollectActivity.class);
                    startActivity(i);
                    break;
                case R.id.menu_cancel:
                    Intent intent2 = new Intent("com.example.broadcastreceiver");
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent2);
                    break;
                case R.id.menu_locate:
                    AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("查看当前位置的天气");
                    builder.setMessage("是否使用该功能，该功能仅会根据位置获取天气状况，并不会泄露你的隐私信息。");
                    builder.setCancelable(true);
                    builder.setNegativeButton("取消",(dialog, which) -> {dialog.dismiss();});
                    builder.setPositiveButton("确定",(dialog, which) -> {
                        Intent intentLocate = new Intent(MainActivity.this, LocateActivity.class);
                        startActivity(intentLocate);
                    });
                    builder.show();
                    break;
                case R.id.menu_dynamic:
                    Intent intentDynamic = new Intent(MainActivity.this, DynaActivity.class);
                    startActivity(intentDynamic);
                    break;
                case R.id.meun_about:
                    startActivity(new Intent(MainActivity.this, AboutMeActivity.class));
            }
            return true;

        });
        Boolean isThis = true;
        Intent i = getIntent();
        if (i.getStringExtra(DESIGN) != null) {
            if (i.getStringExtra(DESIGN).equals("design")) {
                fragmentList.add(new ZhanKuFragment());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
            } else if (i.getStringExtra(DESIGN).equals("news")) {
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new NewsFragment());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
            } else if (i.getStringExtra(DESIGN).equals("history")) {
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(todayFrag);
                fragmentList.add(new RecommendFrag());
            } else if (i.getStringExtra(DESIGN).equals("jokes")) {
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new RecommendFrag());
                fragmentList.add(new JokeFragment());
            }
            isThis = false;
        }
        if ((isWifiConn || isMobileConn) && isThis) {
            fragmentList.add(new ZhanKuFragment());
            fragmentList.add(new NewsFragment());
            fragmentList.add(todayFrag);
            fragmentList.add(new JokeFragment());
        } else {
            fragmentList.add(new NullFragment());
            fragmentList.add(new NullFragment());
            fragmentList.add(new NullFragment());
            fragmentList.add(new NullFragment());
        }
        adapter = new MyAdapter(getSupportFragmentManager(), fragmentList);
        unScroll.setOffscreenPageLimit(4);
        unScroll.setAdapter(adapter);
        bl.setMode(BottomNavigationBar.MODE_SHIFTING);
        bl.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE);
        bl.addItem(new BottomNavigationItem(R.mipmap.bottom_news_1, "设计").setActiveColorResource(R.color.colorPrimary))
                .addItem(new BottomNavigationItem(R.mipmap.bottom_travel_1, "新闻").setActiveColorResource(R.color.colorPrimary))
                .addItem(new BottomNavigationItem(R.mipmap.bottom_ticket_1, "历史").setActiveColorResource(R.color.colorPrimary))
                .addItem(new BottomNavigationItem(R.mipmap.bottom_joke_1, "笑话").setActiveColorResource(R.color.colorPrimary))
                .setFirstSelectedPosition(0)
                .initialise();
        bl.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                unScroll.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
//        tabBeanLis.add(new TabBean("新闻",R.mipmap.bottom_news,R.mipmap.bottom_news_1,1));
//        tabBeanLis.add(new TabBean("天气",R.mipmap.bottom_travel,R.mipmap.bottom_travel_1,1));
//        tabBeanLis.add(new TabBean("历史上的今天",R.mipmap.bottom_ticket,R.mipmap.bottom_ticket_1,1));
//        tabBeanLis.add(new TabBean("笑话",R.mipmap.bottom_joke,R.mipmap.bottom_joke_1,1));
//
//        bottomLayout.setBottom(this,tabBeanLis,unScroll);
        unScroll.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                switch (position) {
                    case 0:
                        getSupportActionBar().setTitle("设计");
                        toolbar.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        getSupportActionBar().setTitle("新闻");
                        toolbar.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        toolbar.setTitle("历史上的今天");
                        toolbar.setVisibility(View.VISIBLE);
                        break;
                    case 3:
                        toolbar.setTitle("笑话");
                        toolbar.setVisibility(View.VISIBLE);
                        break;

                }
            }

            @Override
            public void onPageSelected(int position) {
                bl.selectTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        EventBus.getDefault().register(this);
//        AVObject avObject=new AVObject("TestObject");
//        avObject.put("words","hi future");
//        avObject.saveInBackground(new SaveCallback() {
//            @Override
//            public void done(AVException e) {
//                if(e==null)
//                {
//                    Log.i(TAG, "done: success");
//                }
//            }
//        });
        navImage.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 1);
        });
        if (isWifiConn || isMobileConn) {
            updatePic();
        } else {
            Toast.makeText(this, "请打开网络连接", Toast.LENGTH_SHORT).show();
        }
        tv_header.setText(AVUser.getCurrentUser().getUsername());
//        getUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            try {
                navImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData()));
                mImageBytes = getBytes(getContentResolver().openInputStream(data.getData()));
                AVObject avObject = new AVObject("Todo");
                avObject.put("owner", AVUser.getCurrentUser());
                avObject.put("images", new AVFile("todoPic", mImageBytes));
                avObject.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            if (isWifiConn || isMobileConn) {
                                updatePic();
                            } else {
                                Toast.makeText(MainActivity.this, "请打开网络连接", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buf = new byte[bufferSize];
        int len;
        while ((len = inputStream.read(buf)) != -1) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public void updatePic() {
        AVQuery<AVObject> query = new AVQuery<>("Todo");
        query.orderByAscending("createAt");
        query.include("owner");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (list.size() - 1 >= 0) {
                    String url = list.get(list.size() - 1).getAVFile("images").getUrl();
                    if (url != null) {
                        Glide.with(MainActivity.this)
                                .load(url)
                                .centerCrop()
                                .transform(new GlideCircleTransform(MainActivity.this))
                                .into(navImage);
                    }
                }
            }
        });
    }

    public void getUserInfo() {
        OkHttpClient client = OkHttpUtils.getOkHttpClient();
        client.newCall(RequestUtils.requestGET(NewsApi.URL._User + AppConfigUtils.getInstance().getLoginInfo(this).getObjectId()))
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.i(TAG, "onResponse: " + result);
                        final PersonInfoResponse personInfo = new Gson().fromJson(result, PersonInfoResponse.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_header.setText(personInfo.getUsername() + "");
                            }
                        });
                    }
                });

    }

    @Subscribe
    public void handleMessage(MessageEvent messageEvent) {
        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu2, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDawLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.menu_collect:
                Intent i = new Intent(MainActivity.this, CollectActivity.class);
                startActivity(i);
                break;
            case R.id.menu_scan:
                Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_shake:
                Intent intent1 = new Intent(MainActivity.this, ShakeActivity.class);
                startActivity(intent1);
                break;
            case R.id.menu_date:
                new DatePickerDialog(MainActivity.this, (view, year1, month1, dayOfMonth) -> {
                    setTitle(year + "-" + month + "-" + dayOfMonth);
                    todayFrag.getData(month + 1, dayOfMonth);

                }, year, month, day).show();
                break;
            case R.id.menu_photo:
                ShowCodeFragment showCodeFragment = new ShowCodeFragment();
                showCodeFragment.show(getSupportFragmentManager(), "Show");
                break;
            case R.id.menu_clear:
                DataClearManagerUtils.clearAllCache(App.getInstance());
                Toast.makeText(this, "清除缓存成功", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private static Boolean isQuit = false;
    private Timer timer = new Timer();

    @Override
    public void onBackPressed() {
        if (isQuit == false) {
            isQuit = true;
            Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
            TimerTask timerTask;
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    isQuit = false;
                }
            };
            timer.schedule(timerTask, 1500);
        } else {
            finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
    //    long lastTime=0;
//    @Override
//    public void onBackPressed() {
//        long curTime=System.currentTimeMillis();
//        if((curTime-lastTime)>300){
//            Toast.makeText(this, "再按一次后退键退出App", Toast.LENGTH_SHORT).show();
//            lastTime=curTime;
//            return;
//        }
//        else {
//            finish();
//        }
//        super.onBackPressed();
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
